#include "ws.request.h"

#ifdef DEBUG
#include <iostream>
#endif

TOB::WS::Request::Request(std::string request) {
  size_t found;
  std::string req = request;
  
  // get scheme
  found = req.find("://");
  if (found == std::string::npos) {
    throw TOB::WS::RequestException(request);
    return;
  }
  _scheme = req.substr(0, found);
  req = req.substr(found + 3);
  
  // get host
  if (req.length() > 0) {
    found = req.find("/");
    _host = req.substr(0, found);
    req = (found == std::string::npos) ? "" : req.substr(found + 1);
  }
  else {
    throw TOB::WS::RequestException(request);
    return;
  }
  
  // get path to file
  if (req.length() > 0) {
    found = req.find("?");
    _pathToFile = req.substr(0, found);
    req = req.substr(found + 1);
  }
  else {
    _pathToFile = "";
  }
  
  // get params
  if (found != std::string::npos) {
    int pos;
    std::string tmp;
    do {
      found = req.find("&");
      tmp = req.substr(0, found);
      req = req.substr(found + 1);
      pos = tmp.find("=");
      int p = tmp.find("&");
      if (pos > p || (pos == std::string::npos && p != std::string::npos)) {
        pos = p;
      }
      _params[tmp.substr(0, pos)] = (pos == std::string::npos) ? "" : tmp.substr(pos + 1);
    } while (found != std::string::npos);
  }
  
  //get func
  _func = TOB::WS::Function::Unknown;
       if (_scheme.compare("getpage")  == 0) _func = TOB::WS::Function::GetPage;
  else if (_scheme.compare("getfile")  == 0) _func = TOB::WS::Function::GetFile;
  else if (_scheme.compare("sendfile") == 0) _func = TOB::WS::Function::SendFile;
  else if (_scheme.compare("response") == 0) _func = TOB::WS::Function::Response;
  
#ifdef DEBUG
  std::cout << "created request: " << this << std::endl;
#endif
}

TOB::WS::Request::~Request() {
#ifdef DEBUG
  std::cout << "deleted request: " << this << std::endl;
#endif
}

std::string TOB::WS::Request::getScheme() {
  return _scheme;
}
std::string TOB::WS::Request::getHost() {
  return _host;
}
std::string TOB::WS::Request::getPathToFile() {
  return _pathToFile;
}
std::map<std::string, std::string> TOB::WS::Request::getParams() {
  return _params;
}

TOB::WS::Function::Type TOB::WS::Request::getFunc() {
  return _func;
}

TOB::WS::RequestException::RequestException(std::string req) {
  TOB::Log::error("WebServer::Request: parse error (string: " + req + ")");
}
